/* $RCSFile: CRMImageBookSelect.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/PageModules/CRMImageBook/CRMImageBookSelect.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:56:46  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.Settings;
using AddonNice.Settings.CRMImage;

using AddonNice.CRMImage;
using AddonNice.CRMImage.UI;

using Telerik.Web.UI;


using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CRMImage
{
    public partial class CRMImageBookSelect : UserControl
    {

        public string AlbumPath
        {
            get
            { 
                return (string)ViewState[ImStr.MetaAlbumPath]; 
            }
            set
            {
                ViewState[ImStr.MetaAlbumPath] = value;
            }
        }

        public int ImageLibId
        {
            get
            { 
                return (int)ViewState[ImStr.ImageLibId]; 
            }
            set
            {
                ViewState[ImStr.ImageLibId] = value;
            }
        }


        public string RequestEntityName
        {
            get
            { 
                return (string)ViewState[ImStr.RequestEntityName]; 
            }
            set
            {
                if ( CrmImageTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect RequestEntityName SET value: {0}", value),CrmImageTrace.Sw.Info);
                ViewState[ImStr.RequestEntityName] = value;
            }
        }

        /// <summary>
        /// This parameter is set from CRMImageBookAdd
        /// </summary>
        public Guid EntityID
        {
            get
            {
                object ob = ViewState[ImStr.EntityID];
                if (ob != null)
                    return (Guid)ob;
                return Guid.Empty;
            }
            set
            {
                ViewState[ImStr.EntityID] = value;
            }
        }


        protected bool _disableEditForm = true;

        public Boolean DisableEditForm
        {
            get
            {
                return _disableEditForm;
            }
            set
            {
                _disableEditForm = value;
            }
        }

        public string GetImageUrl(object ob)
        {
            if ( CrmImageTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect GetImageUrl ob: {0}", ob),CrmImageTrace.Sw.Info);
            string url                  =   Config.PortalSpecialImagesPath+"/ImageNotAvailable.gif";
            if ( ob is CRMImageListItem )
                url                     =   AlbumPath+"/"+((CRMImageListItem)ob).ImageUrl;
            else if (ob is System.Data.Common.DbDataRecord)
            {
                ImageMetaData metadata  =   new ImageMetaData();
                metadata.LoadXml((string)((System.Data.Common.DbDataRecord)ob)[ImStr.DBMetadataXml]);
                url                     =   AlbumPath+"/"+metadata.GetMetadata(ImStr.ThumbnailFilename);            
            }
            if ( CrmImageTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect GetImageUrl url: '{0}'", url),CrmImageTrace.Sw.Info);
            return url;
        }

        public string GetShortDescription(object ob)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect GetShortDescription ob: {0}", ob),CrmImageTrace.Sw.Info);
            if ( ob is CRMImageListItem )
                return ((CRMImageListItem)ob).ShortDescription;
            return string.Empty;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect Page_Load BEG IsPostBack: {0}", IsPostBack),CrmImageTrace.Sw.Info);
            DetailsGrid.EditIndexes.Add(0);
            if (!IsPostBack)
            {
                DataBind();
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookSelect Page_Load END.",CrmImageTrace.Sw.Info);
        }

        public void InsertSelected()
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect InsertSelected BEG Items.Count: {0}", ImageSelectGrid.SelectedItems.Count),CrmImageTrace.Sw.Info);
            if ( ImageSelectGrid.SelectedItems.Count <= 0 )
                return;
            CRMImageDB CRMImagedB           =   new CRMImageDB();
            foreach (GridDataItem dataItem in ImageSelectGrid.SelectedItems)
            {
                int ImageId                 =   -1;
                SqlDataReader dr            =   null;
                try
                {
                    string strVal           =   dataItem[ImStr.DBImageId].Text;
                    if (CrmImageTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect InsertSelected ImageId: {0}", strVal), CrmImageTrace.Sw.Info);
                    ImageId                 =   int.Parse(strVal);
                    // Read the image from DB to copy XMl parameters
                    dr                      =   CRMImagedB.GetCRMImage(ImageId);
                    dr.Read();
                    //If this is a new CRMImageBook add it to the database
                    CRMImagedB.AddCRMImageBook(RequestEntityName, EntityID, ImageId, 0, (string)dr[ImStr.DBMetadataXml], (string)dr[ImStr.DBShortDescription]);
                    dr.Close();
                }
                catch (Exception ex)
                {
                    if (CrmImageTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookSelect InsertSelected EntityID: {0}, ImageId: {1}, ex: {2}", EntityID, ImageId, ex), CrmImageTrace.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( dr != null )
                        dr.Close();
                }
            }
            // Invalidate the dataObject cache
            string ckey                     =   "CRMAllImages"+EntityID.ToString();
            AddonNice.Settings.Cache.CurrentCache.Remove(ckey);
            //Rebind Grid to remove unwanted records
            ImageSelectGrid.DataSource      =   null;
            ImageSelectGrid.Rebind();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookSelect InsertSelected END.",CrmImageTrace.Sw.Info);
        }
        

        protected void DetailsGrid_ItemUpdated(object source, GridUpdatedEventArgs e)
        {
            e.KeepInEditMode = true;
        }

        void DetailsGrid_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                e.Item.PreRender += new EventHandler(DetailsGrid_ItemPreRender);
            }
        }

        private void DetailsGrid_ItemPreRender(object sender, EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect DetailsGrid_ItemPreRender DisableEditForm: {0}, e: {1}, Items.Count: {2}", 
                    DisableEditForm,sender,DetailsGrid.MasterTableView.Items.Count),CrmImageTrace.Sw.Info);
            GridDataItem dataItem       =   (GridDataItem)sender;
            // Hide first and only row
            dataItem.Visible            =   false;

            GridEditFormItem editItem   =   dataItem.EditFormItem;

            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect DetailsGrid_ItemPreRender editItem.Controls.Count: {0}.", 
                    editItem.Controls.Count),CrmImageTrace.Sw.Info);
            foreach (WebControl ctrl in editItem.Controls)
            {
                ctrl.Enabled        =   false;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect DetailsGrid_ItemPreRender Ctrl ID: '{0}'.", 
                        ctrl.ID),CrmImageTrace.Sw.Info);
            }
            Control ctl =   editItem.FindControl("UpdateButton");
            if ( ctl != null)
            {
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect DetailsGrid_ItemPreRender updateButton found in editItem: {0}",ctl),CrmImageTrace.Sw.Info);
                ctl.Visible =   false;
            }
            ctl =   editItem.FindControl("CancelButton");
            if ( ctl != null)
            {
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]CRMImageBookSelect DetailsGrid_ItemPreRender cancelButton found in editItem.",CrmImageTrace.Sw.Info);
                ctl.Visible =   false;
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookSelect DetailsGrid_ItemPreRender END.",CrmImageTrace.Sw.Info);
        }


        /// <summary>
        /// Sent from page container
        /// </summary>
        /// <param name="eventArgument"></param>
        public void SetAction(string eventArgument)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect SetAction eventArg: {0}", eventArgument),CrmImageTrace.Sw.Info);
            switch (eventArgument)
            {
                 case "AddNewProduct": // the current selected image allowing several adds
                    InsertSelected();
                    break;
            }
        }

        void ImageSelectGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect ImageSelectGrid_NeedDataSource BEG EntityID: {0}.",EntityID),CrmImageTrace.Sw.Info);
            List<CRMImageListItem>  lst     =   CRMImageListItemDAL.getImages(EntityID,ImageLibId);
            ImageSelectGrid.DataSource      =   lst;
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect ImageSelectGrid_NeedDataSource END Count: {0}.",lst.Count),CrmImageTrace.Sw.Info);
        }


        void ImageSelectGrid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect ImageSelectGrid_ItemCommand BEG CommandName: {0}.",e.CommandName),CrmImageTrace.Sw.Info);
            if (e.CommandName == "RowClick" && e.Item is GridDataItem)
            {
                e.Item.Selected             =   true;
                int ImageId                 =   (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ImageId"]; 
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect ImageSelectGrid_ItemCommand ImageId: {0}.",ImageId),CrmImageTrace.Sw.Info);
                LoadDetail(ImageId);
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookSelect ImageSelectGrid_ItemCommand END.",CrmImageTrace.Sw.Info);
        }

        /// <summary>
        ///  Load the detail grid
        /// </summary>
        private void LoadDetail(int ImageId)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect LoadDetail BEG ImageId: {0}.", ImageId),CrmImageTrace.Sw.Info);
            SqlDataReader reader        =   null;
            try
            {
                reader                  =   new CRMImageDB().GetCRMImage(ImageId);
                DetailsGrid.DataSource  =   reader;
                DetailsGrid.DataBind();
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookSelect LoadDetail ImageId: {0}, ex: {1}", ImageId,ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageBookSelect LoadDetail END.",CrmImageTrace.Sw.Info);
        }

        void CRMImageBookSelect_PreRender(object sender, EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookSelect OnInit BEG.",CrmImageTrace.Sw.Info);
            if (ImageSelectGrid.SelectedIndexes.Count == 0 && ImageSelectGrid.Items.Count > 0)
            {
                ImageSelectGrid.SelectedIndexes.Add(0);
                int ImageId         =   int.Parse(ImageSelectGrid.MasterTableView.Items[0]["ImageId"].Text); 
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookSelect ImageSelectGrid_ItemCommand ImageId: {0}.",ImageId),CrmImageTrace.Sw.Info);
                LoadDetail(ImageId);
            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookSelect OnInit BEG.",CrmImageTrace.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageBookSelect OnInit END.",CrmImageTrace.Sw.Info);
        }

        private void InitializeComponent()
        {
            Load                            +=  new System.EventHandler(Page_Load);
            DetailsGrid.ItemCreated         +=  new GridItemEventHandler(DetailsGrid_ItemCreated);
            ImageSelectGrid.NeedDataSource  +=  new GridNeedDataSourceEventHandler(ImageSelectGrid_NeedDataSource);
            ImageSelectGrid.ItemCommand     +=  new GridCommandEventHandler(ImageSelectGrid_ItemCommand);
            PreRender                       +=  new EventHandler(CRMImageBookSelect_PreRender);
            
            //ImageDataSource1.Selecting  +=  new ObjectDataSourceSelectingEventHandler(ImageDataSource1_Selecting);
            //ImageDataSource1.Selected   +=  new ObjectDataSourceStatusEventHandler(ImageDataSource1_Selected);
        }

        #endregion

    }
}